const {
  MemberModel
} = require('../../../utils/member-model.js');
var memberModel = new MemberModel();
const {
  CurrencyShopModel
} = require('../../../utils/currencyshop-model.js')
const currencyShopModel = new CurrencyShopModel()
var utils =
  require("../../../utils/util.js");
const {
  globalData
} = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    shopInfo: {},
    memberTransferRelation: null,
    hasAssets: false,
    isLogin: false,
    isIphoneX: globalData.isIphoneX,
    src: 'https://oss.kiscloud.net/wechat/images/no_phone.png',
    cardShowView: true, //绑定门店卡弹出层
    gameCurrency: 0, //游戏币
    gameTicket: 0, //游戏券
    lottery: 0, //飞豆
    integral: 0, //积分
    exchangeCoupon: 0, //兑换券
    discountCoupon: 0, //优惠券
    memberName: "", //会员名称
    memberImg: "", //会员头像
    leverCode: "", //会员等级code
    leverName: "", //等级名称
    cardList: [], //卡列表
    memberId: "", //会员ID
    letters: 0, // 消息条数
    svipType: "", //SVIP类型 1:是 0:否
    menus: [],
    activeIdx: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const merchantId = wx.getStorageSync('merchantId');
    currencyShopModel.queryMenu({
      merchantId,
      moduleTypes: [6]
    }).then(data => {
      const menus = data.modules[0].contents.filter(item => {
        return item.options.nav_type == '1'
      })
      let activeIdx = 0
      menus.forEach((item, index) => {
        if (item.options.nav_redirect_type == '3') {
          activeIdx = index
        }
      })
      this.setData({
        menus,
        activeIdx
      })
    }).catch(err => {
      wx.showToast({
        title: `${err.error}`,
        icon: 'none'
      })
    })
    let shopInfo = wx.getStorageSync('shopInfo')
    let memberTransferRelation = wx.getStorageSync('memberTransferRelation')
    let hasAssets = wx.getStorageSync('hasAssets')
    this.setData({
      shopInfo,
      memberTransferRelation,
      hasAssets
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.setData({
      isLogin: globalData.isLogin
    }, function () {
      this.getUserAssetSummary(); //会员资产汇总
      this.getUserInfo(); //会员信息
      this.getCardList(); //查询是否有会员卡
      this.getUnreadMessage(); // 查询未读消息
    })
  },
  getUnreadMessage() {
    if (globalData.isLogin) {
      memberModel.getUnreadNum({
        merchantId: wx.getStorageSync('merchantId'),
        messageStatus: 0
      }).then(data => {
        this.setData({
          letters: data || 0,
        })
      }).catch(err => {
        wx.showToast({
          title: `${err.error}`,
          icon: 'none',
          duration: 2000
        })
      })
    }
  },
  /**
   * 会员资产汇总
   */
  getUserAssetSummary: function () {
    if (globalData.isLogin) {
      memberModel.userAssetSummary({
        merchantId: wx.getStorageSync('merchantId')
      }).then(data => {
        var that = this;
        that.setData({
          gameCurrency: utils.formatCurrency(data.coinTotal),
          gameTicket: utils.formatCurrency(data.gameCouponTotal),
          lottery: utils.formatCurrency(data.lotteryTotal),
          integral: utils.formatCurrency(data.integralTotal),
          exchangeCoupon: utils.formatCurrency(data.exchangeCouponTotal),
          discountCoupon: utils.formatCurrency(data.discountCouponTotal)
        });
      }).catch(err => {
        wx.showToast({
          title: `${err.error}`,
          icon: 'none',
          duration: 2000
        })
      })
    }
  },

  /**
   *微信会员信息
   */
  getUserInfo: function () {
    if (globalData.isLogin) {
      memberModel.userInfo({
        merchantId: wx.getStorageSync('merchantId')
      }).then(data => {
        wx.setStorageSync('memberId', data.memberId);
        var that = this;
        that.setData({
          memberName: data.nickname || "", //会员名称
          src: data.avatarUrl || "https://oss.kiscloud.net/wechat/images/no_phone.png", //会员头像
          leverCode: data.memberLevel ? 'V' + data.memberLevel : "V0", //会员等级
          leverName: data.memberLevelName ? data.memberLevelName : "", //等级名称
          memberId: data.memberId ? '会员ID：' + data.memberId : "", //会员ID
          svipType: data.svipType //SVIP类型 1: 是 0: 否
        });
      }).catch(err => {
        wx.showToast({
          title: `${err.error}`,
          icon: 'none',
          duration: 2000
        })
      })
    }
  },

  formSubmit(e) {
    if (globalData.isLogin) {
      memberModel.userMessage({
        merchantId: wx.getStorageSync('merchantId'),
        formIds: [e.detail.formId]
      }).then(() => {
        this.goQRCode()
      }).catch(() => {
        this.goQRCode()
      })
    }
  },

  /**
   * 会员卡列表
   */
  getCardList: function () {
    if (globalData.isLogin) {
      memberModel.userCardList({
        merchantId: wx.getStorageSync('merchantId')
      }).then(data => {
        if (data && data.length > 0) {
          this.setData({
            cardList: data
          });
        }
      }).catch(err => {
        wx.showToast({
          title: `${err.error}`,
          icon: 'none',
          duration: 2000
        })
      })
    }
  },

  //跳转到个人资料
  goInformation: function () {
    if (globalData.isLogin) {
      wx.reportAnalytics('member_nickname')
      wx.navigateTo({
        url: '/pages/memberCenter/information/personalData/index'
      })
    } else {
      wx.navigateTo({
        url: '/pages/login/index'
      })
    }
  },

  /**
   *绑定门店卡弹出层
   */
  setAddCard: function () {
    if (this.data.cardList.length > 0) {
      this.judgeIsLogin('/pages/memberCenter/cardLIst/index')
    } else {
      this.judgeIsLogin('/pages/memberCenter/addCard/index')
      wx.reportAnalytics('member_bindcard')
    }
  },

  //跳转到游戏币或者游戏券
  goGameHtml: function (event) {
    var type = event.currentTarget.dataset.type; //页面类型
    this.judgeIsLogin('/pages/memberCenter/gameCurrency/index?type=' + type)
  },
  //跳转到飞豆
  goLottery: function () {
    this.judgeIsLogin('/pages/memberCenter/lottery/index')
  },
  //跳转到我的订单
  goOrderList: function () {
    wx.reportAnalytics('member_order')
    this.judgeIsLogin('/pages/memberCenter/myOrder/index')
  },
  // 跳转到领取赠品
  goGetGift() {
    this.judgeIsLogin('/pages/memberCenter/getGift/index')
  },
  //跳转到积分
  goIntegral: function () {
    this.judgeIsLogin('/pages/memberCenter/integral/index')
  },
  //跳转到二维码页面
  goQRCode: function (e) {
    wx.reportAnalytics('member_qrcode')
    wx.reLaunch({
      url: '/pages/memberCenter/QRCode/index'
    })
    // this.judgeIsLogin('/pages/memberCenter/QRCode/index')
  },

  //跳转到附近门店
  goNearbyShop: function () {
    wx.reportAnalytics('member_shop')
    // this.judgeIsLogin('/pages/memberCenter/nearbyShop/index')
    wx.navigateTo({
      url: '/pages/memberCenter/nearbyShop/index'
    })
  },
  goLetterCenter() {
    wx.reportAnalytics('member_letter')
    this.judgeIsLogin('/pages/memberCenter/letterCenter/index')
  },
  //跳转到会员权益
  goGrade: function () {
    wx.reportAnalytics('member_level')
    this.judgeIsLogin('/pages/memberCenter/grade/index')
  },
  //跳转到兑换券
  goExchangeCoupon: function () {
    wx.reportAnalytics('member_exchange')
    this.judgeIsLogin('/pages/memberCenter/exchangeCoupon/index')
  },
  //跳转到优惠券
  goDiscountCoupon: function () {
    wx.reportAnalytics('member_coupon')
    this.judgeIsLogin('/pages/memberCenter/discountCoupon/index')
  },
  //跳转到奖品碎片
  goPrizeList: function () {
    this.judgeIsLogin('/pages/memberCenter/prize/prizePieces/index')
  },
  //跳转到svip会员页面
  gosVip: function (event) {
    if (this.data.svipType == 0) {
      this.judgeIsLogin('/pages/currencyShop/chooseStore/index?sVipType=' + this.data.sVipType)
    } else if (this.data.svipType == 1) {
      this.judgeIsLogin('/pages/svip/member/index')
    }
  },
  // 判断是否授权登录
  judgeIsLogin(url) {
    if (globalData.isLogin) {
      wx.navigateTo({
        url
      })
    } else {
      // wx.showModal({
      //   content: '请先授权登录哦',
      //   cancelColor: '#231916',
      //   confirmText: '登录',
      //   confirmColor: '#6AB64E',
      //   success(res) {
      //     if (res.confirm) {
      //       wx.navigateTo({
      //         url: '/pages/login/index',
      //       })
      //     }
      //   }
      // })
    }
  }
})